package com.jinwei.qunguanjia.web.wechat.service;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class WxAsyncTemplateMessageService {

    @Resource(name="wxMpService")
    private WxMpService wxMpService;

    @Async
    public void sendTemplateMessageByOpenId(String openId, String templateId, List<WxMpTemplateData> data, String pagePath) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .data(data)
                .templateId(templateId)
                .build();
        // 跳转小程序相关配置【跳转的小程序必须是公众号关联的小程序！！！】
        //templateMessage.setMiniProgram(new WxMpTemplateMessage.MiniProgram(maAppId, pagePath,false));
        //发起推送
        String msg = null;
        try {
            msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.info("WxAsyncTemplateMessageService WxErrorException: ", e);
        }
        log.info("推送成功：" + msg);
    }
}
